﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using E5_KhuyenMaiVang.Models;
using System.Data;

namespace E5_KhuyenMaiVang.Controllers
{
    public class CheckoutController : Controller
    {
        GoldDealEntities db = new GoldDealEntities();        

        public ActionResult StepOne()
        {
            return View();
        }

        public ActionResult StepTwo()
        {
            List<string> infos = (List<string>)Session["Info"];
            MemberView mv = new MemberView();
            mv.MemberName = infos[0];
            mv.Address = infos[1];
            mv.Phone = infos[2];
            mv.Email = infos[3];
            mv.CMND = infos[4];
            return View(mv);
        }

        public ActionResult StepThree()
        {
            if (Session["OnlinePayment"] != null)
            {
                Payment p = (Payment)Session["OnlinePayment"];
                return View(p);
            }
            return View();
        }

        public ActionResult StepFour()
        {
            return View();
        }
        
        [HttpPost]
        public ActionResult PostStepOne()
        {
            if (Session["Info"] != null)
                return RedirectToAction("StepTwo");
            if (Session["LogOn"] != null)
            {
                MembershipUser user = Membership.GetUser((string)Session["LogOn"]);
                MEMBER member = db.MEMBER.First(m => m.Account == (Guid)user.ProviderUserKey);
                return View("StepTwo", MemberManager.ToMemberView(member));
            }
            return View("StepTwo");
        }

        [HttpPost]
        public ActionResult PostStepTwo(MemberView mv)
        {
            List<string> infos = new List<string>();
            infos.Add(mv.MemberName);
            infos.Add(mv.Address);
            infos.Add(mv.Phone);
            infos.Add(mv.Email);
            infos.Add(mv.CMND);
            Session["Info"] = infos;
            if(Session["PayKind"] == null)
                Session["PayKind"] = 1;
            return RedirectToAction("StepThree");
        }

        [HttpPost]
        public ActionResult PostStepThree(Payment p)
        {
            if (p.Kind == 2)
                Session["OnlinePayment"] = p;
            return View("StepFour");
        }

        [HttpPost]
        public ActionResult ReturnToCart()
        {
            return RedirectToAction("ViewCart", "Member");
        }

        public ActionResult ChangeKind1()
        {
            Session["PayKind"] = 1;
            return View("StepThree");
        }

        public ActionResult ChangeKind2()
        {
            Session["PayKind"] = 2;
            return View("StepThree");
        }

        [HttpPost]
        public ActionResult Purchase()
        {
            List<DEAL> DealInCart = (List<DEAL>)Session["Cart"];
            List<int> ListQuantity = (List<int>)Session["ListQuantity"];
            List<string> infos = (List<string>)Session["Info"];

            string name = infos[0];
            string address = infos[1];
            string phone = infos[2];
            string email = infos[3];
            string cmnd = infos[4];

            int memberID = 0;
            MEMBER member = null;
            try
            {
                member = db.MEMBER.Single(p => (p.MemberName.Equals(name) &&
                    p.Address.Equals(address) &&
                    p.Phone.Equals(phone) &&
                    p.Email.Equals(email) &&
                    p.CMND.Equals(cmnd)));
            }
            catch { }

            if (member != null)
                memberID = member.MemberID;
            else
            {
                MEMBER newMember = new MEMBER();
                newMember.MemberName = infos[0];
                newMember.Address = infos[1];
                newMember.Phone = infos[2];
                newMember.Email = infos[3];
                newMember.CMND = infos[4];
                newMember.Birth = DateTime.Now.AddYears(-18);
                newMember.Gender = 1;
                if (Session["LogOn"] != null)
                {
                    MembershipUser user = Membership.GetUser((string)Session["LogOn"]);
                    newMember.Account = (Guid)user.ProviderUserKey;
                }
                db.AddToMEMBER(newMember);
                db.SaveChanges();
                memberID = newMember.MemberID;
            }
            

            if ((int)Session["PayKind"] == 1)
            {
                AddToDB(DealInCart, ListQuantity, memberID, 1);
                Session["Cart"] = null;
            }
            else
            {
                Payment p = (Payment)Session["OnlinePayment"];                
                double sum = 0;
                for (int i = 0; i < DealInCart.Count; i++)
                {
                    sum += DealInCart[i].Discount;
                }
                sum /= 21000;
                //4806029673924095
                PayPalGateway temp = new PayPalGateway();
                PayPalReturn rv = temp.Pay("123", string.Format("{0:0.##}", sum), "Nguyen", "Duc", null, null, null, "084", "Viet Nam", "1", "Visa", p.CardNumber,
                    "099", p.Month.ToString(), p.Year.ToString());
                if (rv.IsSucess)
                {
                    AddToDB(DealInCart, ListQuantity, memberID, 2);
                    Session["Cart"] = null;
                }
                else
                {
                    return PartialView("PurchaseFail");
                }

            }
            db.SaveChanges();            
            return PartialView("PurchaseSuccessful");
        }

        private void AddToDB(List<DEAL> DealInCart, List<int> ListQuantity, int memberID, int status)
        {
            for (int i = 0; i < DealInCart.Count; i++)
            {
                DEAL de = DealInCart[i];
                DEAL deal = db.DEAL.Single(d => d.DealID == de.DealID);
                deal.SoldQuantity += ListQuantity[i];
                if (deal.SoldQuantity <= deal.MaxQuantity)
                {
                    if (deal.SoldQuantity == deal.MaxQuantity)
                    {
                        deal.StatusID = db.DEAL_STATUS.Single(s => s.StatusName.Equals("Hết hàng")).StatusID;
                    }
                    if (deal.SoldQuantity >= deal.MinQuantity)
                    {
                        deal.StatusID = db.DEAL_STATUS.Single(s => s.StatusName.Equals("Đủ tối thiểu")).StatusID;
                    }

                    for (int j = 0; j < ListQuantity[i]; j++)
                    {
                        VOUCHER v = new VOUCHER();
                        v.PurchaseDate = DateTime.Now;
                        v.MemberID = memberID;
                        v.DealID = deal.DealID;
                        v.Price = deal.Discount;
                        v.StatusID = status;
                        db.AddToVOUCHER(v);
                    }
                }
            } 
        }
    }
}